package com.bigstar.lolkor;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.content.res.AssetManager.AssetInputStream;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class Utils {
	public static final String DATA_PATH = "/sdcard/Android/data/LOLDATA/";
	public static final String RINGTONE_PATH = "/sdcard/media/audio/ringtones/";

	public static Bitmap skin;

	public static boolean isNetwork(Context context) {
		ConnectivityManager cmgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo wifiInfo = cmgr
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo mobileNetworkInfo = cmgr
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		NetworkInfo lteInfo = cmgr
				.getNetworkInfo(ConnectivityManager.TYPE_WIMAX);
		NetworkInfo activeNetwork = cmgr.getActiveNetworkInfo();
		boolean wifi = false;
		boolean mobileNetwork = false;
		boolean lte = false;
		if (mobileNetworkInfo != null) {
			if (mobileNetworkInfo.isAvailable()
					&& mobileNetworkInfo.isConnected()) {
				mobileNetwork = true;
			}
		}
		if (activeNetwork != null) {
			if (activeNetwork.isAvailable() && activeNetwork.isConnected()) {
				mobileNetwork = true;
			}
		}
		if (wifiInfo != null) {
			if (wifiInfo.isAvailable() && wifiInfo.isConnected()) {
				wifi = true;
			}
		}
		if (lteInfo != null) {
			if (lteInfo.isAvailable() && lteInfo.isConnected()) {
				lte = true;
			}
		}
		if (wifi || mobileNetwork || lte) {
			return true;
		}
		return false;
	}

	public static String GetDevicesUUID(Context mContext) {

		final TelephonyManager tm = (TelephonyManager) mContext
				.getSystemService(Context.TELEPHONY_SERVICE);

		final String tmDevice, tmSerial, androidId;
		tmDevice = "" + tm.getDeviceId();
		tmSerial = "" + tm.getSimSerialNumber();
		androidId = ""
				+ android.provider.Settings.Secure.getString(
						mContext.getContentResolver(),
						android.provider.Settings.Secure.ANDROID_ID);

		UUID deviceUuid = new UUID(androidId.hashCode(),
				((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
		String deviceId = deviceUuid.toString();

		return deviceId;
	}

	public static void setRingtone(Context context, int champid,
			String settingType) {
		String filepath = "/sdcard/media/audio/ringtones/testmusic4.mp3";
		File file = new File(filepath);
		if (!file.exists()) {
			file.mkdirs();
		}
		try {
			ContentValues values = new ContentValues();
			values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
			values.put(MediaStore.MediaColumns.TITLE,
					ChampionData.champions.get(champid).name_en);
			values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
			values.put(settingType, true);
			Uri uri = MediaStore.Audio.Media.getContentUriForPath(file
					.getAbsolutePath());
			context.getContentResolver().delete(
					uri,
					MediaStore.MediaColumns.DATA + "=\""
							+ file.getAbsolutePath() + "\"", null);
			Uri newUri = context.getContentResolver().insert(uri, values);
			RingtoneManager.setActualDefaultRingtoneUri(context,
					RingtoneManager.TYPE_RINGTONE, newUri);
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(context, "벨소리 설정에 실패했습니다.", Toast.LENGTH_SHORT)
					.show();
			return;
		}
		Toast.makeText(context, "벨소리 설정이 완료되었습니다.", Toast.LENGTH_SHORT).show();
	}

	public static Bitmap loadBitmap(Context context, String path,
			String fileName) {
		Bitmap bm = null;
		String str = Environment.getExternalStorageState();
		if (str.equals(Environment.MEDIA_MOUNTED)) {
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			Log.i("wwwwwww", DATA_PATH + path + "/" + fileName);
			bm = BitmapFactory.decodeFile(DATA_PATH + path + "/" + fileName);
		}
		return bm;
	}

	public static Bitmap loadBitmap(Context context, String urlStr) {
		Bitmap bitmap = null;
		AssetManager mngr = context.getResources().getAssets();
		InputStream is = null;
		try {
			is = mngr.open(urlStr, AssetManager.ACCESS_BUFFER);
			bitmap = BitmapFactory.decodeStream(is);
		} catch (Exception e) {

		}
		return bitmap;
	}

	public static Bitmap getBitmapFromUrl(String imageURL) {
		Bitmap imgBitmap = null;
		HttpURLConnection conn = null;
		BufferedInputStream bis = null;
		try {
			URL url = new URL(imageURL);
			conn = (HttpURLConnection) url.openConnection();
			conn.connect();
			int nSize = conn.getContentLength();
			bis = new BufferedInputStream(conn.getInputStream(), nSize);
			imgBitmap = BitmapFactory.decodeStream(bis);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
				}
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
		return imgBitmap;
	}

	public static String getXMLFileFromAssets(Context context, String path)
			throws IOException {
		AssetManager assetManager = context.getResources().getAssets();
		AssetInputStream ais = (AssetInputStream) assetManager.open(path);
		BufferedReader br = new BufferedReader(new InputStreamReader(ais));
		String line;
		StringBuilder data = new StringBuilder();
		while ((line = br.readLine()) != null)
			data.append(line);
		return data.toString();
	}

	public static void saveBitmap(Context context, Bitmap bm, String path,
			String fileName, Boolean option) {
		String str = Environment.getExternalStorageState();
		if (str.equals(Environment.MEDIA_MOUNTED) && option) {
			String dirPath = DATA_PATH + path;
			File dir = new File(dirPath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			File file = new File(DATA_PATH + path + "/" + fileName);
			if (file.exists()) {
				return;
			}
			FileOutputStream fos = null;
			try {
				fos = new FileOutputStream(file);
				bm.compress(CompressFormat.JPEG, 80, fos);
			} catch (FileNotFoundException e) {
				Toast.makeText(context, "에러", Toast.LENGTH_SHORT).show();
			} catch (SecurityException e) {
				Toast.makeText(context, "에러", Toast.LENGTH_SHORT).show();
			} catch (Exception e) {
				Toast.makeText(context, "에러", Toast.LENGTH_SHORT).show();
			} finally {
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}

	public static void showDialog(Context context, String title, String message) {
		AlertDialog.Builder alert = new AlertDialog.Builder(context);
		alert.setTitle(title).setMessage(message);
		alert.setNegativeButton("닫기", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			}
		});
		alert.setIcon(R.drawable.icon);
		alert.create().show();
	}

	public static String sendPost(String url, int teamVal, int num,
			String teamName) throws SocketTimeoutException, IOException {

		// Create a new HttpClient and Post Header
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);

		try {
			// Add your data
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
			nameValuePairs.add(new BasicNameValuePair("idx", "" + teamVal));
			nameValuePairs.add(new BasicNameValuePair("num", "" + num));
			nameValuePairs.add(new BasicNameValuePair("strTeamName", teamName));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			// Execute HTTP Post Request
			HttpResponse response = httpclient.execute(httppost);
			return EntityUtils.toString(response.getEntity());
		} catch (Exception e) {
			// TODO Auto-generated catch block
		}
		return "";
	}

	public static String unescape(String inp) {
		StringBuffer rtnStr = new StringBuffer();
		char[] arrInp = inp.toCharArray();
		int i;
		for (i = 0; i < arrInp.length; i++) {
			if (arrInp[i] == '%') {
				String hex;
				if (arrInp[i + 1] == 'u') { // 유니코드.
					hex = inp.substring(i + 2, i + 6);
					i += 5;
				} else { // ascii
					hex = inp.substring(i + 1, i + 3);
					i += 2;
				}
				try {
					rtnStr.append(Character.toChars(Integer.parseInt(hex, 16)));
				} catch (NumberFormatException e) {
					rtnStr.append("%");
					i -= (hex.length() > 2 ? 5 : 2);
				}
			} else {
				rtnStr.append(arrInp[i]);
			}
		}

		return rtnStr.toString();
	}

	public static String replaceAll(String temp, String s, String c) {

		while (true) {
			if (temp.indexOf(s) != -1)
				temp = temp.replace(s, c);
			else
				break;
		}
		return temp;
	}

	public static boolean loadObject(Context context, String pathUrl, String urlName) {
		String str = Environment.getExternalStorageState();
		if (str.equals(Environment.MEDIA_MOUNTED)) {
			File f = new File(DATA_PATH+pathUrl+ "3d_obj.obj");
			if(f.exists()){
				return true;
			}
			FileOutputStream fos = null;
			try {
				URL url = new URL("http://ghdnjs9012.megaplug.kr/"+pathUrl+ "3d_obj.txt");
				if(urlName.charAt(0) >= 'A' && urlName.charAt(0) <= 'G'){
					url = new URL("http://ghdnjs9012.megaplug.kr/"+pathUrl+ "3d_obj.txt");
				}else if(urlName.charAt(0) >= 'H' && urlName.charAt(0) <= 'N'){
					url = new URL("http://ghdnjs1423.megaplug.kr/"+pathUrl+ "3d_obj.txt");
				}else if(urlName.charAt(0) >= 'O' && urlName.charAt(0) <= 'U'){
					url = new URL("http://leesolo369.megaplug.kr/"+pathUrl+ "3d_obj.txt");
				}else{
					url = new URL("http://fantartist.megaplug.kr/"+pathUrl+ "3d_obj.txt");
				}
				InputStream is = url.openStream();
				
				fos = new FileOutputStream(DATA_PATH + pathUrl + "3d_obj.obj");
				double len = 0;
				double tmp = 0;
				byte[] buf = new byte[1024];
				while ((len = is.read(buf)) > 0) {
					tmp += len / 1024 / 1024;
					fos.write(buf, 0, (int) len);
				}
				fos.close();
				is.close();
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			} finally {
			}
		}
		return true;
	}
	
	public static boolean loadMtl(Context context, String pathUrl, String urlName) {
		String str = Environment.getExternalStorageState();
		if (str.equals(Environment.MEDIA_MOUNTED)) {
			File f = new File(DATA_PATH+"3d/"+ "obj_mtl.mtl");
			if(f.exists()){
				return true;
			}
			FileOutputStream fos = null;
			try {
				URL url = new URL("http://fantartist.megaplug.kr/"+"3d/"+ "obj_mtl.txt");
				InputStream is = url.openStream();
				
				fos = new FileOutputStream(DATA_PATH + "3d/" + "obj_mtl.mtl");
				double len = 0;
				double tmp = 0;
				byte[] buf = new byte[1024];
				while ((len = is.read(buf)) > 0) {
					tmp += len / 1024 / 1024;
					fos.write(buf, 0, (int) len);
				}
				fos.close();
				is.close();
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			} finally {
			}
		}
		return true;
	}
	
	public static boolean loadTexture(Context context, String pathUrl, String urlName) {
		String str = Environment.getExternalStorageState();
		if (str.equals(Environment.MEDIA_MOUNTED)) {
			File f = new File(DATA_PATH+pathUrl+ "texture.jpg");
			if(f.exists()){
				return true;
			}
			Bitmap imgBitmap = null;
			HttpURLConnection conn = null;
			BufferedInputStream bis = null;
			FileOutputStream fos = null;
			try {
				URL url = new URL("http://ghdnjs9012.megaplug.kr/"+pathUrl+ "texture.jpg");
				if(urlName.charAt(0) >= 'A' && urlName.charAt(0) <= 'G'){
					url = new URL("http://ghdnjs9012.megaplug.kr/"+pathUrl+ "texture.jpg");
				}else if(urlName.charAt(0) >= 'H' && urlName.charAt(0) <= 'N'){
					url = new URL("http://ghdnjs1423.megaplug.kr/"+pathUrl+ "texture.jpg");
				}else if(urlName.charAt(0) >= 'O' && urlName.charAt(0) <= 'U'){
					url = new URL("http://leesolo369.megaplug.kr/"+pathUrl+ "texture.jpg");
				}else{
					url = new URL("http://fantartist.megaplug.kr/"+pathUrl+ "texture.jpg");
				}
				conn = (HttpURLConnection) url.openConnection();
				conn.connect();
				int nSize = conn.getContentLength();
				bis = new BufferedInputStream(conn.getInputStream(), nSize);
				imgBitmap = BitmapFactory.decodeStream(bis);
				
				fos = new FileOutputStream(f);
				imgBitmap.compress(CompressFormat.JPEG, 100, fos);
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			} finally {
				if (fos != null){
					try {
						fos.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		return true;
	}
}
